"""
基础模型类
"""
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

# 数据库实例，将在__init__.py中设置
db = None
BaseModel = None

def set_db(database):
    """设置数据库实例"""
    global db, BaseModel
    db = database
    
    # 设置数据库实例后，定义BaseModel
    class BaseModel(db.Model):
        """所有模型的基类，包含公共字段和方法"""
        __abstract__ = True
        
        # 公共字段
        id = db.Column(db.Integer, primary_key=True)
        created_at = db.Column(db.DateTime, default=datetime.now)
        updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
        
        def to_dict(self):
            """将模型转换为字典"""
            return {
                column.name: getattr(self, column.name)
                for column in self.__table__.columns
            }
        
        def update_from_dict(self, data):
            """从字典更新模型属性"""
            for key, value in data.items():
                if hasattr(self, key) and key not in ['id', 'created_at']:
                    setattr(self, key, value)
            self.updated_at = datetime.now()
            db.session.commit()
        
        @classmethod
        def create(cls, **kwargs):
            """创建新记录"""
            instance = cls(**kwargs)
            db.session.add(instance)
            db.session.commit()
            return instance
        
        def update(self, **kwargs):
            """更新记录"""
            for key, value in kwargs.items():
                if hasattr(self, key) and key not in ['id', 'created_at']:
                    setattr(self, key, value)
            self.updated_at = datetime.now()
            db.session.commit()
            return self
        
        def delete(self):
            """删除记录"""
            db.session.delete(self)
            db.session.commit()
        
        @classmethod
        def get_by_id(cls, id):
            """根据ID获取记录"""
            return cls.query.get(id)
        
        @classmethod
        def get_all(cls):
            """获取所有记录"""
            return cls.query.all()
        
        @classmethod
        def get_by_filter(cls, **kwargs):
            """根据条件筛选记录"""
            return cls.query.filter_by(**kwargs).all()
        
        @classmethod
        def get_first_by_filter(cls, **kwargs):
            """根据条件获取第一条记录"""
            return cls.query.filter_by(**kwargs).first()
        
        @classmethod
        def count(cls, **kwargs):
            """根据条件统计记录数"""
            if kwargs:
                return cls.query.filter_by(**kwargs).count()
            return cls.query.count()
        
        def __repr__(self):
            return f"<{self.__class__.__name__} {self.id}>"
    
    # 将BaseModel添加到全局命名空间
    globals()['BaseModel'] = BaseModel

def get_db():
    """获取数据库实例"""
    return db